package com.white.interfaceone.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.net.ssl.SSLException;

/**
 * @version v1.0
 * @ProjectName: interfaceone
 * @ClassName: FaceIDCread
 * @Description: TODO(访问旷视科技身份证识别系统)  doc:https://console.faceplusplus.com.cn/documents/5671702
 * @Author: sunbo@pgytesting.cn
 * @Date: 2019/5/6 17:11
 */
public class FaceIDCread {


    private static Logger log = LoggerFactory.getLogger(FaceIDCread.class);

    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static Map getFaceIDCread(String imgFile) {
        File dir = new File("");
        log.info("存储图片的绝对路径为" + dir.getAbsolutePath());
        String path = dir.getAbsolutePath() + "/iDCardImg" + UtilMethod.uuidMd5Encryption();
        if (!ImgBase64Utils.Base64ToImage(imgFile, path)) {
            return UtilMethod.StringToJson("{\"statusCode\":3000}");
        }
        File file = new File(path);
        byte[] buff = getBytesFromFile(file);
        String url = "https://api-cn.faceplusplus.com/cardpp/v1/ocridcard";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, byte[]> byteMap = new HashMap<>();
        map.put("api_key", "_iV384iSCWENQ9opRUxKEiJxiLNOZEfs");
        map.put("api_secret", "yvYq0SFU7vwYrf8eQx8o5PyO14B2BEYn");
        map.put("return_landmark", "1");
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file", buff);
        File filePath = new File(path);
        if (!filePath.delete())
            return UtilMethod.StringToJson("{\"statusCode\":3000}");
        try {

            byte[] bacd = post(url, map, byteMap);
            String str = new String(bacd);
            str = String.valueOf(UtilMethod.StringToJson(str).get("cards")).substring(1, String.valueOf(UtilMethod.StringToJson(str).get("cards")).length() - 2) + ",\"statusCode\":2000}";
            log.info("\n图片身份证识别信息：" + str);
            return UtilMethod.StringToJson(str);
        } catch (Exception e) {
            log.info("请求获取数据异常");
            return UtilMethod.StringToJson("{\"statusCode\":3000}");
        }
    }


    protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }


    public static void main(String[] args) throws Exception {

        String base64 = ImgBase64Utils.ImageToBase64ByLocal("C:/Users/frosty/Pictures/扫描/扫描_20190220.png");
        getFaceIDCread(base64);
    }
}
